﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Text;
using System.Web;
using System.Web.Security;
using LX.Core.Auth;
using LX.Web.Utils;

namespace LX.Web.Auth
{

    /// <summary>
    /// 
    /// </summary>
    public class CookiePersistentProvider 
    {
        private string cookiename = "";


        public CookiePersistentProvider(string name)
        {
            cookiename = name;
        }

        private string GetCookieName()
        {
            return cookiename;
        }

        public void Save(String principalid, TicketPersistentOption option)
        {
            if (string.IsNullOrWhiteSpace(principalid)) return;
            if (option.Type == TicketPersistentType.INSESSION)
            {
                HttpHelper.WriteCookie(GetCookieName(), LX.Core.Cryptography.DES.Encrypt(principalid));
            }
            else
            {
                HttpHelper.WriteCookie(GetCookieName(), LX.Core.Cryptography.DES.Encrypt(principalid),option.TimeOut);
            }
        }

        public String GetPrincipalId()
        {
            var str = HttpHelper.GetCookie(GetCookieName());
            if (string.IsNullOrWhiteSpace(str)) return null;
            try
            {
                var id = LX.Core.Cryptography.DES.Decrypt(str);
                return id;
            }catch
            {
                return null;
            }
        }


        public void Clear(string principalid)
        {
            if (string.IsNullOrWhiteSpace(principalid)) return;
            HttpHelper.WriteCookie(GetCookieName(), LX.Core.Cryptography.DES.Encrypt(principalid),-1);
        }
    }
}
